import React, { useEffect, useRef, useState } from 'react'
import { useLocation } from 'react-router-dom'
import request from '../utils/request';
import MarkdownEditor from '../components/MdEditor';

import styles from '../style/blogpreview.module.less'
import { Blog } from './bloglist';

interface BlogPreviewProps {
  blog?: Blog
  handleClose?: () => void
}

const BlogPreview: React.FC<BlogPreviewProps> = (props) => {
  const { blog } = props
  const location = useLocation()
  const [value, setValue] = useState('')

  useEffect(() => {
    if (!/^\/blog\/\d+$/.test(location.pathname)) return
    async function fetchBlog() {
      if (blog) {
        setValue(blog.content)
      }
      const result = await request(`/api${location.pathname}`)
      setValue(result.data.data[0].content)
    }
    let timer =  setTimeout(() => {
      fetchBlog()
    }, 4)
    return () => clearTimeout(timer)
  }, [location.pathname, blog])
  return (<div className={styles.container}>
    {props.blog && <span className={styles.closeBtn} onClick={props.handleClose}>X</span>}
    <MarkdownEditor
      value={value}
      readOnly
      editorInlineStyle={{
        marginTop: 15,
        height: 'calc(100vh - 68px - 48px - 15px)', 
        width: '100%',
        border: 'none'
      }}
      view={{
        menu: false,
        md: false,
        html: true
      }}
    />
  </div>)
}

export default BlogPreview
